Skip to main content

C# ASP.NET Core SDK Methods Reference

Welcome to the C# ASP.NET Core SDK Reference. This guide will help you integrate TideCloak into your ASP.NET Core application, manage user authentication, and ensure secure access. Follow the steps below to implement the methods used with the SDK in your application.


1. Prerequisites

Before you begin, ensure you have:

  • A TideCloak instance running locally or on a server.
  • A realm and a client configured in TideCloak.
  • Basic knowledge of C# and .NET.
  • .NET Core SDK installed on your machine.

2. Create a New ASP.NET Core Project

dotnet new

Create a new ASP.NET Core web application using the command line:

dotnet new webapp -o MyKeycloakApp

This command initializes a basic ASP.NET Core project in the MyKeycloakApp directory.

Open Project

After creating the project, open it in your chosen IDE Terminal:

Example:

cd MyKeycloakApp

3. Install NuGet Packages

dotnet add package

Install the required NuGet packages to enable TideCloak integration:

dotnet add package OpenIddict.Client
dotnet add package OpenIddict.Client.AspNetCore
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
dotnet add package Microsoft.IdentityModel.Protocols.OpenIdConnect

Packages Installed:

  • OpenIddict.Client: Handles client operations for OpenIddict.
  • OpenIddict.Client.AspNetCore: Integrates OpenIddict client with ASP.NET Core.
  • Microsoft.AspNetCore.Authentication.JwtBearer: Enables JWT token authentication.
  • Microsoft.AspNetCore.Authentication.OpenIdConnect: Adds OpenID Connect support.
  • Microsoft.IdentityModel.Protocols.OpenIdConnect: Manages OpenID Connect protocols.

4. Configuration

AddAuthentication()

Configure authentication middleware in Program.cs:

builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Authority = "http://localhost:8080/realms/realm";
options.ClientId = "myclient";
options.ResponseType = OpenIdConnectResponseType.Code;
options.SaveTokens = true;
options.RequireHttpsMetadata = false;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.GetClaimsFromUserInfoEndpoint = true;
options.ClaimActions.MapJsonKey(ClaimTypes.Name, "preferred_username");
options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
options.ClaimActions.MapJsonKey("sub", "sub");
});

Options:

  • Authority: The URL of your TideCloak realm. This is where your application will send authentication requests.
    • Example:

      options.Authority = "http://localhost:8080/myrealm/";
  • ClientId: The client ID registered in TideCloak. This identifies your application in the TideCloak realm.
    • Example:

      options.ClientId = "exampleClient";
  • ResponseType: Specifies the OpenID Connect response type. Typically set to code to indicate that the client is requesting an authorization code.
    • Example:

      options.ResponseType = OpenIdConnectResponseType.Code;
  • SaveTokens: Saves the tokens (ID token, access token, refresh token) returned by TideCloak for later use.
    • Example:

      options.SaveTokens = true;
  • RequireHttpsMetadata: Determines whether TideCloak's metadata should be retrieved over HTTPS. Should be set to true in production to ensure secure communication.
    • Example (Development):

      options.RequireHttpsMetadata = false;
    • Example (Production):

      options.RequireHttpsMetadata = true;
  • Scope: Defines the OAuth2 scopes requested by the application. Common scopes include openid, profile, and email.
    • Example:

      options.Scope.Add("openid");
      options.Scope.Add("profile");
      options.Scope.Add("email");
  • GetClaimsFromUserInfoEndpoint: When set to true, retrieves additional user information (claims) from the UserInfo endpoint.
    • Example:

      options.GetClaimsFromUserInfoEndpoint = true;
  • ClaimActions.MapJsonKey: Maps JSON keys from the UserInfo endpoint to claims in your application. Common claims include preferred_username, email, and sub.
    • Example:

      options.ClaimActions.MapJsonKey(ClaimTypes.Name, "preferred_username");
      options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
      options.ClaimActions.MapJsonKey("sub", "sub");

5. Authentication Handling

Login()

TideCloak automatically redirects users to the login page, but you can manually trigger the login process:

return Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectDefaults.AuthenticationScheme);

Options:

  • RedirectUri: Specifies the URI to redirect to after login.

Example:

return Challenge(new AuthenticationProperties { RedirectUri = "/dashboard" }, OpenIdConnectDefaults.AuthenticationScheme);

Logout()

To log the user out, use the SignOut method:

return SignOut(new AuthenticationProperties { RedirectUri = "/" },
CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme);

Options:

  • RedirectUri: Specifies the URI to redirect to after logout.

Example:

return SignOut(new AuthenticationProperties { RedirectUri = "/goodbye" },
CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme);

Register()

Redirect the user to the registration page:

return Redirect("http://localhost:8080/realms/myrealm/protocol/openid-connect/registrations");

Options:

  • RedirectUri: Specifies the URI to redirect to after registration.

Example:

return Redirect("http://localhost:8080/realms/demo/protocol/openid-connect/registrations");

AccountManagement()

Redirect the user to the TideCloak account management console:

return Redirect("http://localhost:8080/realms/myrealm/account");

Example:

return Redirect("http://localhost:8080/realms/demo/account");

6. Accessing User Information

User.Identity

Display user details in your views:

@if (User.Identity.IsAuthenticated)
{
<p><strong>Name:</strong> @User.Identity.Name</p>
<p><strong>Email:</strong> @User.FindFirst("email")?.Value</p>
<p><strong>Subject (sub):</strong> @User.FindFirst("sub")?.Value</p>
}

User Claims:

  • Name: The preferred username.
  • Email: The user's email address.
  • sub: The unique identifier for the user.

Example:

<p><strong>Email:</strong> @User.FindFirst("email")?.Value</p>

7. Debugging and Logging

EnableLogging()

Enable logging to troubleshoot authentication issues:

builder.Services.AddAuthentication(options =>
{
options.EnableLogging = true;
// Other configurations
});

Options:

  • EnableLogging: When set to true, additional debug information is logged.

Example:

options.EnableLogging = true;

8. Security

TLS/SSL

Ensure RequireHttpsMetadata is set to true in production for secure communication:

options.RequireHttpsMetadata = true;

Options:

  • RequireHttpsMetadata: Ensures metadata is retrieved over HTTPS.

Example:

options.RequireHttpsMetadata = true;

Enecryption

Decryption